package net.food.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;

import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.jfinal.kit.JsonKit;
import net.food.AliPayLoginUtil.AliUrlUtil;
import net.food.AliPayLoginUtil.GetOrderNo;
import net.food.remotecommon.entity.Order;
import net.food.remotecommon.entity.Shop;
import net.food.remotecommon.entity.ShopAliPay;
import net.food.remotecommon.service.OrderService;
import net.food.remotecommon.service.ShopAliPayService;
import net.food.remotecommon.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @
 * @author Wx
 * 2017年5月20日
 */
@Controller
@RequestMapping(value = "/ali_WapPay")
public class AliPayController {


    @Autowired
    private ShopService shopService;

	@Autowired
	private OrderService orderService;

    @Autowired
	private ShopAliPayService shopAliPayService;



	@RequestMapping(value = "/pay", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public void wapPay(@RequestParam String shopId,@RequestParam String money, HttpServletRequest request, HttpServletResponse response) throws IOException {
   // 商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = GetOrderNo.getOrderNo();

		// 订单名称，必填
		String subject = "智慧云点单消费";
		// 付款金额，必填
		String total_amount=money;
		// 商品描述，可空
		String body = "吃鸡";
		// 销售产品码 必填
		String product_code="QUICK_WAP_PAY";
		Order order=new Order();
		order.setShopId(shopId);
		order.setOrderNo(out_trade_no);
		order.setTotalPrice(Double.valueOf(money));
		order.setPayType(2);
		order.setCreateTime(new Date());
		orderService.persist(order);
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliUrlUtil.appId, AliUrlUtil.APP_PRIVATE_KEY, "json", AliUrlUtil.CHARSET, AliUrlUtil.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
		AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
		model.setOutTradeNo(out_trade_no);
		model.setSubject(subject);
		model.setTotalAmount(total_amount);
		model.setBody(body);
		model.setProductCode(product_code);;
		alipay_request.setBizModel(model);
		// 设置异步通知地址
		alipay_request.setNotifyUrl(AliUrlUtil.redirect_uri);
		// 设置同步地址
		alipay_request.setReturnUrl(AliUrlUtil.url);

		// form表单生产
		String form = "";
		// 调用SDK生成表单
		try {
            form = alipayClient.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AliUrlUtil.CHARSET);
			System.out.println(form);
			response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

	}

   @RequestMapping(value = "/notify_url",method = {RequestMethod.POST, RequestMethod.GET})
   @ResponseBody
	public void notify_url(HttpServletRequest request) {

	   Map<String, String> params = new HashMap<String, String>();
	   Map<String, String[]> requestParams = request.getParameterMap();
	   Set<String> keySet = requestParams.keySet();
	   String out_trade_no = "";
	   String trade_status = "";
	   String total_amount = "";
	   for (String key : keySet) {
		   StringBuffer buffer = new StringBuffer();
		   for (String string : requestParams.get(key)) {
			   buffer.append(string);
		   }
		   params.put(key, buffer.toString());
		   if (key.equals("out_trade_no")) {
			   out_trade_no = buffer.toString();// 商户订单号
			   System.out.println(out_trade_no);
		   } else if (key.equals("trade_status")) {
			   trade_status = buffer.toString();// 交易状态
			   System.out.println(trade_status);
		   } else if (key.equals("total_amount")) {
			   total_amount = buffer.toString().substring(0,buffer.toString().length()-3) + "";// 金额
			   System.out.println(total_amount);
		   }
	   }

	   if(trade_status.equals("TRADE_SUCCESS")){
		   Order order=orderService.getByProerties("orderNo",out_trade_no);
		   order.setStatus(1);
		   order.setPayTime(new Date());
		   orderService.update(order);
	   }


	}

	@RequestMapping(value = "/author_qrcode")
	public ModelAndView ali_authorQrcode(ModelAndView modelAndView, @RequestParam String shopId, HttpServletRequest request){
		request.getSession().setAttribute("shopId",shopId);

		String url="http://www.ddera.com/food_customer/ali_WapPay/aliAuthorNotify?shopId="+shopId;
		modelAndView.addObject("url", url);
/*		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2017072207848840", AliUrlUtil.APP_PRIVATE_KEY, "json", "UTF-8", AliUrlUtil.ALIPAY_PUBLIC_KEY, "RSA2");*/
		modelAndView.setViewName("/Ali_autothQRcode");
		return modelAndView;
	}

    /**
	 *            优惠买单
	 * @param modelAndView
	 * @param request
	 * @param shopId
	 * @return
     */
	@RequestMapping(value = "/aliAuthorNotify")
	public ModelAndView aliAuthorNotify(ModelAndView modelAndView,HttpServletRequest request,@RequestParam String shopId){
		ShopAliPay shopAliPay=shopAliPayService.getByProerties("shopId",shopId);
		/**
		*在调用接口之前初始化AlipayClient
		*/
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliUrlUtil.appId, AliUrlUtil.APP_PRIVATE_KEY, "json", AliUrlUtil.CHARSET, AliUrlUtil.ALIPAY_PUBLIC_KEY, "RSA2");

		Shop shop=shopService.get(shopId);
		modelAndView.addObject("shop",shop);

	/*	Shop shop=shopService.get(shopId);
		modelAndView.addObject("shop",shop);*/
		modelAndView.setViewName("/Preferential_pay");
		return modelAndView;
	}

	@RequestMapping(value = "/changeMoeny",method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
    public String  getChangmonty(@RequestParam String money){

		return money;
	}

    /**
	 *  支付成功
	 * @param modelAndView
	 * @param request
	 * @return
     */
    @RequestMapping(value = "/successPay")
	public ModelAndView  successPay(ModelAndView modelAndView,HttpServletRequest request){

		    modelAndView.setViewName("/successPay");
            return modelAndView;


	}
	
}
